package com.example.controller;

import com.example.common.Result;
import com.example.entity.User;
import com.example.service.IUserService;
import com.example.utils.JwtUtil;
import com.example.utils.MD5Utils;
import org.intellij.lang.annotations.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ljw
 * @version 1.0
 * @Date 2024/9/11 19:32
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 根据id 查用户
     * @param id
     * @return
     */
    @GetMapping("/one")
    public Result findById(Integer id){
        User user= userService.findById(id);
        return Result.success(user);
    }

    /**
     * 查询全部用户
     * @return
     */
    @GetMapping("/all")
    public Result findAll(){
        List<User> user=userService.findAll();
        return Result.success(user);
    }

    /**
     * 登录接口
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result findUserByLogin(@Pattern("^\\S{5,16}") String username, @Pattern("^\\S{5,16}")String password){
        User user = userService.findByName(username);
        if(user==null){
            return Result.error("用户不存在！");
        }
        if(user.getPassword().equals(MD5Utils.code(password))){
            String token = JwtUtil.genToken(user.getId().toString(),user.getUsername());
            return Result.success(token);
        }else{
            return Result.error("密码错误！");
        }

    }

    /**
     * 注册接口
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result register(@Pattern("^\\S{5,16}")String username,@Pattern("^\\S{5,16}")String password){
        User u=userService.findByName(username);
        if(u==null){
            userService.add(username,password);
            return Result.success();
        }else{
            return Result.error("该用户已被注册");
        }
    }

    /**
     * 根据id 更新用户信息
     * @param user
     * @return
     */
    @GetMapping("/update")
    public Result updateById(User user){
        int i=userService.updateById(user);
        if(i>0){
            return Result.success("更新成功");
        }else{
            return Result.error("更新失败");
        }
    }
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id){
        int i =userService.deleteById(id);
        if(i>0){
            return Result.success("更新成功");
        }else{
            return Result.error("更新失败");
        }
    }
    //    新增修改
    @PostMapping
    public Result save(@RequestBody User user){
         userService.saveUser(user);
         return Result.success("更新或添加成功！");
    }
}
